package com.cntaiping.royal.bass.core.controller;

import com.cntaiping.royal.bass.common.util.QiNiuPutFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 通用控制器
 *
 * @author huangheng
 * @date 2019/03/29
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    private static Logger logger = LoggerFactory.getLogger(CommonController.class);

    /**
     * 图片上传
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = {"/upload"})
    public Object upload(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> result = new HashMap<String, Object>();

        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());

        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> multiFileMap = multiRequest.getMultiFileMap();

            List<MultipartFile> fileSet = new LinkedList<>();
            for (Entry<String, List<MultipartFile>> temp : multiFileMap.entrySet()) {
                fileSet = temp.getValue();
            }
            if (fileSet.size() == 0) {
                result.put("msg", "上传失败");
                result.put("code", -1);
                return result;
            }
            try {
                MultipartFile temp = fileSet.get(0);
                if (temp.getSize() >= 10 * 1024 * 1024) {
                    result.put("msg", "文件不能大于10M");
                    result.put("code", -1);
                    return result;
                }


                File file = this.MultipartFileToFile(temp);


                // 文件类型
                String fileType = temp.getOriginalFilename().substring(temp.getOriginalFilename().lastIndexOf(".") + 1);

                String fileUrl = QiNiuPutFile.upload(file, fileType);
                result.put("msg", fileUrl);
                result.put("code", 1);

//				Map<String, Object> map = new PutFile().put64image(file, fileType);
//				if (map.get("code").equals("1000")) {
//					result.put("msg", map.get("url"));
//					result.put("code", 1);
//
//					//上传七牛完成后删除本地文件
//	                File deleteFile = new File(System.getProperty("user.dir")+"/"+temp.getOriginalFilename());
//	                if (deleteFile.exists()){
//	                    deleteFile.delete();
//	                }
//				} else {
//					result.put("msg", map.get("url"));
//					result.put("code", -1);
//				}
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                result.put("msg", "上传失败");
                result.put("code", -1);
            }
        } else {
            result.put("msg", "上传失败");
            result.put("code", -1);
        }
        return result;
    }

    /**
     * MultipartFile转file
     *
     * @param file
     * @return
     */
    private File MultipartFileToFile(MultipartFile file) throws Exception {
        File f = null;

        InputStream is = file.getInputStream();
        f = new File(file.getOriginalFilename());
        OutputStream os = new FileOutputStream(f);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        is.close();

        return f;
    }

}
